package routers

import (
	"net/http"

	"gitee.com/xjieinfo/xjnac/ctrls"
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"github.com/gin-gonic/gin"
)

var Router *gin.Engine

func init() {
	Router = gin.Default()
	store := cookie.NewStore([]byte("secret"))
	Router.Use(sessions.Sessions("mysession", store))
}

func SetupRouter() *gin.Engine {

	//静态目录配置
	Router.Static("/web", "ui/dist")

	Router.GET("/", func(c *gin.Context) {
		c.Redirect(http.StatusMovedPermanently, "/web")
	})
	Router.GET("/code", ctrls.GetCheckCode)
	Router.GET("/proxy_error", ctrls.ProxyError)

	Router.GET("/ServicesList", ctrls.ServicesList)   //服务列表
	Router.GET("/ServiceHealth", ctrls.ServiceHealth) //检查服务健康情况
	Router.DELETE("/ServiceDel", ctrls.ServiceDel)    //删除服务
	Router.PUT("/ServiceDisable", ctrls.ServiceDisable)    //禁用服务
	Router.PUT("/ServiceEnable", ctrls.ServiceEnable)    //启用服务

	Router.GET("/RpcxList", ctrls.RpcxList) //rpcx服务列表

	Router.GET("/config/list", ctrls.ConfigList)
	Router.GET("/config/add", ctrls.ConfigAdd)
	Router.GET("/config/view", ctrls.ConfigView)
	Router.GET("/config/update", ctrls.ConfigUpdate)
	Router.GET("/config/delete", ctrls.ConfigDelete)
	Router.GET("/config/get", ctrls.GetConfig)
	//Router.GET("/health", utils.Health)
	//Router.GET("/refresh", utils.Refresh)
	//Router.GET("/xjie/user/login", c_xjie.XjieLogin)
	////授权拦截
	//Router.Use(Authorize())
	//
	user := Router.Group("/user")
	{
		user.GET("/login", ctrls.XjieLogin)
		user.GET("/info", ctrls.XjieUserInfo)
		user.DELETE("/logout", ctrls.XjieLogout) //退出登陆
		//xjie.GET("/user/userlist", c_xjie.XjieUserList)//用户列表
		//xjie.GET("/user/usergrouplist", c_xjie.XjieUserGroupList)//用户组列表
		//xjie.GET("/user/disable", c_xjie.XjieUserDisable)//禁用用户
		//xjie.GET("/user/enable", c_xjie.XjieUserEnable)//启用用户
	}

	return Router
}

/*
func Authorize() gin.HandlerFunc{
	return func(c *gin.Context){
		//fmt.Println(c.Request.URL.Path)
		auth := c.GetHeader("Authorization")
		session := sessions.Default(c)
		token := ""
		if session.Get("token")!=nil{
			token = session.Get("token").(string)
		}
		token = "Bearer "+token
		if auth==token {
			var powers []string
			if session.Get("powers")!=nil{
				powers = session.Get("powers").([]string)
			}
			urlpath := c.Request.URL.Path
			for _,item := range powers{
				if(item==urlpath){
					// 验证通过，会继续访问下一个中间件
					c.Next()
					return
				}
			}
			// 验证不通过，不再调用后续的函数处理
			c.Abort()
			//c.JSON(http.StatusUnauthorized,gin.H{"message":"访问未授权"})
			fmt.Println("访问未授权:"+c.Request.URL.Path)
			c.JSON(http.StatusUnauthorized, new(m_pub.R).Fail("访问未授权"))
			// return可省略, 只要前面执行Abort()就可以让后面的handler函数不再执行
			return
		} else {
			// 验证不通过，不再调用后续的函数处理
			c.Abort()
			//c.JSON(http.StatusUnauthorized,gin.H{"message":"访问未授权"})
			fmt.Println("访问未授权:"+c.Request.URL.Path)
			c.JSON(http.StatusUnauthorized, new(m_pub.R).Fail("访问未授权"))
			// return可省略, 只要前面执行Abort()就可以让后面的handler函数不再执行
			return
		}
	}
}
*/
